<template>
  <div id="noticeAddPage">
    <div style="font-size: 22px; font-weight: bold">新增通知公告</div>
    <div style="height: 16px"></div>
    <a-form
      :model="formDataAdd"
      name="addNotice"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      @finish="doNoticeAdd"
    >
      <a-form-item label="标题" name="title">
        <a-input v-model:value="formDataAdd.title" />
      </a-form-item>
      <a-form-item label="图片" name="picture">
        <a-upload
          list-type="picture-card"
          :show-upload-list="false"
          :custom-request="handleUpload"
          :before-upload="beforeUpload"
        >
          <img
            v-if="formDataAdd?.picture"
            :src="formDataAdd?.picture"
            alt="picture"
            style="width: 70px; height: 70px"
          />
          <div v-else>
            <LoadingOutlined v-if="loading"></LoadingOutlined>
            <PlusOutlined v-else></PlusOutlined>
            <div class="ant-upload-text">点击或拖拽上传图片</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="简介" name="summary">
        <a-textarea v-model:value="formDataAdd.summary" />
      </a-form-item>
      <a-form-item label="通知状态" name="status">
        <a-select v-model:value="formDataAdd.status">
          <a-select-option :value="1">发布</a-select-option>
          <a-select-option :value="0">草稿</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="内容" name="content">
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="formDataAdd.content"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="handleCreated"
          />
        </div>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { reactive } from 'vue'
import { message, type UploadProps } from 'ant-design-vue'
import { addNoticeUsingPost } from '@/api/noticeController.ts'
import router from '@/router'
import { uploadImageUsingPost } from '@/api/fileUploadController.ts'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import myAxios from '@/request.ts'

const formDataAdd = reactive<API.NoticeAddRequest>({
  title: '',
  picture: '',
  content: '',
  summary: '',
  status: 1,
})

const baseUrl = myAxios.defaults.baseURL

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: baseUrl + '/api/upload/image', // 你的图片上传接口地址
      fieldName: 'file', // 上传文件参数名，后端对应的字段

      // 可选：限制上传类型
      allowedFileTypes: ['image/*'],

      // 可选：限制图片大小，单位 KB
      maxFileSize: 5 * 1024 * 1024, // 5MB

      // 可选：自定义插入逻辑（比如后端返回的字段名不是标准格式）
      customInsert(res, insertFn) {
        // res：后端返回结果
        // insertFn(url, alt, href)：插入图片
        if (res.code === 0 && res.data) {
          insertFn(res.data)
        } else {
          message.error('图片上传失败，' + res.message)
        }
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const doNoticeAdd = async () => {
  const res = await addNoticeUsingPost({
    ...formDataAdd,
  })
  if (res.data.code === 0 && res.data.data !== null) {
    message.success('添加成功')
    router.push('/system/notice')
  } else {
    message.error('添加失败, ' + res.data.message)
  }
}

const loading = ref<boolean>(false)

/**
 * 上传图片
 * @param file
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const res = await uploadImageUsingPost({}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      formDataAdd.picture = res.data.data
    } else {
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    console.log('图片上传失败，' + error)
    message.error('图片上传失败，' + error)
  }
  loading.value = false
}

/**
 * 上传前的校验
 * @param file
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 校验图片格式
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 jpg 或 png')
  }
  // 校验图片大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('不能上传超过 2M 的图片')
  }
  return isJpgOrPng && isLt2M
}
</script>

<style scoped>

</style>
